package com.abu.crms.controller;


import cn.hutool.core.util.StrUtil;
import com.abu.common.Resp;
import com.abu.crms.properties.WxProperties;
import com.abu.crms.service.AuthService;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthWeChatOpenRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/user")
@EnableConfigurationProperties(WxProperties.class)
public class RestAuthController {

    @Autowired
    private WxProperties dingProperties;

    @Autowired
    private AuthService authService;

    /**
     * 返回授权地址Url
     *
     * @return
     */
    @RequestMapping("/noAuthorize/render")
    public Resp renderAuth() {
        AuthRequest authRequest = getAuthRequest();
        String redirectUrl = authRequest.authorize(AuthStateUtils.createState());
        if (StrUtil.isNotEmpty(redirectUrl)) {
            return Resp.ok().data("redirectUrl", redirectUrl);
        }
        return Resp.error().msg("获取跳转地址失败");
    }

    @RequestMapping("/noAuthorize/callback")
    public Resp login(AuthCallback callback, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        Object data = authRequest.login(callback).getData();
        String token = this.authService.toLogin(data);
        if (StrUtil.isNotEmpty(token)) {
            response.sendRedirect("http://localhost:8081/#/welcome?token=" + token);
            return Resp.ok();
        }
        return Resp.error().msg("授权失败");
    }

    private AuthRequest getAuthRequest() {
        return new AuthWeChatOpenRequest(AuthConfig.builder()
                .clientId(dingProperties.getClientId())
                .clientSecret(dingProperties.getClientSecret())
                .redirectUri(dingProperties.getRedirectUrl())
                .build());
    }
}